package com.playball.lottery.frm.buyhall;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.ApplicationData;
import com.playball.lottery.JddMainActivity;
import com.playball.lottery.R;
import com.playball.lottery.base.BaseActivity;
import com.playball.lottery.customview.MyDialog;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.frm.help.CaiPiaoHelp;
import com.playball.lottery.frm.kjinfo.KjinfoListByType;
import com.playball.lottery.frm.yhzx.BetProtocolActivity;
import com.playball.lottery.frm.yhzx.BetRecordActivity;
import com.playball.lottery.frm.yhzx.JddRechargeListActivity;
import com.playball.lottery.frm.yhzx.LoginActivity;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.Constants;
import com.playball.lottery.util.ConvertJsonToList;
import com.playball.lottery.util.DefConstants;
import com.playball.lottery.util.FactoryNum;
import com.playball.lottery.util.LotConstants;
import com.playball.lottery.util.MyPreference;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.playball.lottery.R.id.buy_ctzq_bqc_add_match;
import static com.playball.lottery.R.id.buy_ctzq_bqc_clear_match;
import static com.playball.lottery.R.id.buy_ctzq_bqc_issue_and_endtime;
import static com.playball.lottery.R.id.buy_ctzq_bqc_matches_and_endtime;
import static com.playball.lottery.R.id.view_buy_ctzq_bqc_bet;
import static com.playball.lottery.R.id.view_buy_ctzq_bqc_matches;
import static com.playball.lottery.R.id.view_buy_ctzq_jqc_bet;
import static com.playball.lottery.R.id.view_buy_ctzq_jqc_matches;

/**
 * 传统足球 - 半全场
 * @author tanglizhong
 * @version 2014-4-1 下午3:54:49
 */
public class CtzqBqcActivity extends BaseActivity implements View.OnClickListener {
	private View noDataView ;

	/** 顶部标题栏左侧 */
	private TextView buy_ctzq_top_tv_left;
	/** 顶部标题栏右侧 */
	private TextView buy_ctzq_top_tv_right;
	/** 顶部标题栏中间内容 */
	private TextView buy_ctzq_top_tv_title;
	/** 比赛信息布局 */
	private View view_buy_ctzq_bqc_matches;
	/** 期数及截止时间 */
	private TextView buy_ctzq_bqc_issue_and_endtime;
	/** 比赛列表 */
	private RecyclerView buy_ctzq_bqc_list;

	/** 底部菜单栏左侧 */
	private Button buy_ctzq_bottom_tv_left;
	/** 底部菜单栏右侧 */
	private TextView buy_ctzq_bottom_tv_right;
	/** 底部菜单栏中间提示 */
	private TextView buy_ctzq_bottom_tv_title;

	/** 投注布局 */
	private View view_buy_ctzq_bqc_bet;
	/** 投注情况和截止日期 */
	private TextView buy_ctzq_bqc_matches_and_endtime;
	/** 添加比赛按钮 */
	private View buy_ctzq_bqc_add_match;
	/** 清空选项按钮 */
	private View buy_ctzq_bqc_clear_match;
	/** 投注列表 */
	private ListView buy_ctzq_bqc_list_bet;
	/** 投注倍数 */
	private EditText buy_ctzq_bottom_et_a_multiple;
	/** 底部菜单栏左侧 */
	private TextView buy_ctzq_bottom_tv_left_bet;
	/** 底部菜单栏右侧 */
	private TextView buy_ctzq_bottom_tv_right_bet;
	/** 底部菜单栏中间提示 */
	private TextView buy_ctzq_bottom_tv_title_bet;

	/** 投注协议布局 */
	private View view_buy_ctzq_bet_protocol;
	private CheckBox bet_protocol_choice;
	private TextView bet_protocol;

	private PopupWindow m_popupWindow;

	/** 投注数 */
	private int betTotal;
	/** 倍数 */
	private int a_multiple;
	/**
	 * 进球数场次数据
	 */
	private int issueID;
	private String issue;
	private String EndTime;
	private List<CtzqSfcMatche> matches;
	private MatchAdapter matchAdapter;
	private List<CtzqSfcMatche> matchesBet;
	private BetAdapter betAdapter;

	private String paramsStr;


	/** 判断是否从推送通知过来 */
	private Boolean ifPush;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.buy_ctzq_bqc);
		ifPush=getIntent().getBooleanExtra("ifPush",false);
		initView();
		initData();
	}
	@Override//退出当前界面
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			onBack();
		}
		return true;
	}
	@Override//退出方法
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == DefConstants.REQ_CODE_BUYMAIN && resultCode == RESULT_OK) {
			this.finish();
		}
		if (resultCode == RESULT_OK) {
			if (requestCode == DefConstants.REQ_CODE_NO_MONEY_2_RECHARGE) {
				finish();
			}
		}
	}
	private void initView() {
		noDataView = findViewById(R.id.no_data);

		buy_ctzq_top_tv_left = (TextView) findViewById(R.id.buy_ctzq_top_tv_left);
		buy_ctzq_top_tv_right = (TextView) findViewById(R.id.buy_ctzq_top_tv_right);
		buy_ctzq_top_tv_title = (TextView) findViewById(R.id.buy_ctzq_top_tv_title);

		buy_ctzq_top_tv_left.setOnClickListener(this);
		buy_ctzq_top_tv_right.setOnClickListener(this);
		buy_ctzq_top_tv_title.setText("半全场");

		buy_ctzq_top_tv_right.setVisibility(View.VISIBLE);
		// 比赛布局
		view_buy_ctzq_bqc_matches=findViewById(R.id.view_buy_ctzq_bqc_matches);
		buy_ctzq_bottom_tv_left = (Button) findViewById(R.id.buy_ssqxh_Buttondel);
		buy_ctzq_bottom_tv_right = (TextView) findViewById(R.id.buy_ctzq_bottom_tv_right);
		buy_ctzq_bottom_tv_title = (TextView) findViewById(R.id.buy_ctzq_bottom_tv_title);
		buy_ctzq_bottom_tv_right.setOnClickListener(this);
		buy_ctzq_bottom_tv_left.setOnClickListener(this);

		buy_ctzq_bqc_list= (RecyclerView) findViewById(R.id.buy_ctzq_bpc_list);
		buy_ctzq_bqc_issue_and_endtime = (TextView) findViewById(R.id.buy_ctzq_bqc_issue_and_endtime);
		// 投注布局
		view_buy_ctzq_bqc_bet = findViewById(R.id.view_buy_ctzq_bqc_bet);
		buy_ctzq_bqc_matches_and_endtime = (TextView) findViewById(R.id.buy_ctzq_bqc_matches_and_endtime);
		buy_ctzq_bqc_list_bet = (ListView) findViewById(R.id.buy_ctzq_bqc_list_bet);
		buy_ctzq_bottom_et_a_multiple = (EditText) findViewById(R.id.buy_ctzq_bottom_et_a_multiple);
		buy_ctzq_bottom_et_a_multiple.addTextChangedListener(textWatcher);
		buy_ctzq_bottom_tv_left_bet = (TextView) findViewById(R.id.buy_ctzq_bottom_tv_left_bet);
		buy_ctzq_bottom_tv_right_bet = (TextView) findViewById(R.id.buy_ctzq_bottom_tv_right_bet);
		buy_ctzq_bottom_tv_title_bet = (TextView) findViewById(R.id.buy_ctzq_bottom_tv_title_bet);

		buy_ctzq_bottom_tv_left_bet.setOnClickListener(this);
		buy_ctzq_bottom_tv_right_bet.setOnClickListener(this);

		buy_ctzq_bqc_add_match = findViewById(R.id.buy_ctzq_bqc_add_match);
		buy_ctzq_bqc_clear_match = findViewById(R.id.buy_ctzq_bqc_clear_match);
		buy_ctzq_bqc_add_match.setOnClickListener(this);
		buy_ctzq_bqc_clear_match.setOnClickListener(this);

		// 协议布局
		view_buy_ctzq_bet_protocol = LayoutInflater.from(this).inflate(R.layout.bet_protocol_foot, null);
		bet_protocol_choice = (CheckBox) view_buy_ctzq_bet_protocol.findViewById(R.id.bet_protocol_choice);
		bet_protocol = (TextView) view_buy_ctzq_bet_protocol.findViewById(R.id.bet_protocols);
//		bet_protocol.setText(Html.fromHtml("<u>我已阅读并同意《代购合买协议》</u>"));
		bet_protocol.setVisibility(View.VISIBLE);//显示代购合买协议
		bet_protocol_choice.setChecked(true);
		bet_protocol.setOnClickListener(this);
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()){
			case R.id.buy_ctzq_top_tv_left:// 返回
				onBack();
				break;
			case R.id.buy_ctzq_top_tv_right:
				LayoutInflater inflater = LayoutInflater.from(CtzqBqcActivity.this);
				// 小目录框的设置
				View menuview = inflater.inflate(R.layout.public_menulink, null);
				m_popupWindow = new PopupWindow(menuview, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

				m_popupWindow.setBackgroundDrawable(new BitmapDrawable());
				m_popupWindow.setOutsideTouchable(true);
				m_popupWindow.showAtLocation(menuview, Gravity.RIGHT | Gravity.TOP, 0, 0);
				m_popupWindow.showAsDropDown(buy_ctzq_top_tv_right);

				menuview.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						m_popupWindow.dismiss();
					}
				});

				Button public_menulink_Button01 = (Button) menuview.findViewById(R.id.public_menulink_Button01);
				public_menulink_Button01.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Intent intent;
						m_popupWindow.dismiss();
						if (checkUserLogin()) {
							Intent intent0 = new Intent();
							intent0.putExtra("lotID", LotConstants.LOT_ID_BQC);
							intent0.setClass(CtzqBqcActivity.this, BetRecordActivity.class);
							startActivity(intent0);
						} else {
							intent = new Intent(getApplicationContext(), LoginActivity.class);
							startActivityForResult(intent, DefConstants.REQ_CODE_ZQJQC);
						}
					}
				});

				Button public_menulink_Button02 = (Button) menuview.findViewById(R.id.public_menulink_Button02);
				public_menulink_Button02.setVisibility(View.GONE);

				Button public_menulink_Button03 = (Button) menuview.findViewById(R.id.public_menulink_Button03);
				public_menulink_Button03.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						m_popupWindow.dismiss();
						Intent intent;
						intent = new Intent(getApplicationContext(), KjinfoListByType.class);
						intent.putExtra("LottID", "15");
						intent.putExtra("LottName", "半全场");
						startActivity(intent);
					}
				});
				Button public_menulink_Button04 = (Button) menuview.findViewById(R.id.public_menulink_Button04);
				public_menulink_Button04.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						m_popupWindow.dismiss();
						Intent intent = new Intent(getApplicationContext(), CaiPiaoHelp.class);
						intent.putExtra("cp_title", "半全场");
						intent.putExtra("cp_url", "bqc.html");
						startActivity(intent);
					}
				});
				break;
			case R.id.buy_ctzq_bottom_tv_right:// 确定
				int s = getBetCount() - 6;
				if (s >= 0) {
					showBetView();
				} else {
					showTip("您还需选择" + (-s) + "场比赛");
				}
				break;
			case R.id.buy_ssqxh_Buttondel:// 清空
				onClear();
				break;
			case R.id.buy_ctzq_bottom_tv_left_bet://合买
				if (betTotal > 0 && a_multiple > 0) {
					if (!bet_protocol_choice.isChecked()) {
						showTip("需要同意《代购合买协议》才可以继续购买");
						return;
					}
					if (checkUserLogin()) {
						runBetTask2();
					} else {
						Intent intent = new Intent(CtzqBqcActivity.this, LoginActivity.class);
						startActivityForResult(intent, DefConstants.REQ_CODE_ZQRX9);
					}
				} else {
					showTip("您的订单有误，请重新选定");
				}
				break;
			case R.id.buy_ctzq_bottom_tv_right_bet:// 付款
				if (betTotal > 0 && a_multiple > 0) {
					if (!bet_protocol_choice.isChecked()) {
						showTip("需要同意《代购合买协议》才可以继续购买");
						return;
					}
					if (checkUserLogin()) {
						// 执行投注异步任务
						AsyncBetLoader task = new AsyncBetLoader();
						task.execute("207");
					} else {
						Intent intent = new Intent(CtzqBqcActivity.this, LoginActivity.class);
						startActivityForResult(intent, DefConstants.REQ_CODE_ZQJQC);
					}
				} else {
					showTip("您的订单有误，请重新选定");
				}
				break;
			case R.id.buy_ctzq_bqc_add_match: // 添加比赛
				view_buy_ctzq_bqc_bet.setVisibility(View.GONE);
				view_buy_ctzq_bqc_matches.setVisibility(View.VISIBLE);
				matchAdapter.notifyDataSetChanged();
				break;
			case R.id.buy_ctzq_jqc_clear_match:// 清空选项
				matchesBet.clear();
				betAdapter.notifyDataSetChanged();
				showBetTotal();
				for (CtzqSfcMatche match : matches) {
					match.setBet_win(false);
					match.setBet_draw(false);
					match.setBet_lose(false);
					match.setBet_dan(false);
				}
				break;
			case R.id.bet_protocols: // 协议
				startActivityForResult(new Intent(CtzqBqcActivity.this, BetProtocolActivity.class), 0);
				break;
		}
	}
	private void initData() {
		matches = new ArrayList<CtzqSfcMatche>();
		matchesBet = new ArrayList<CtzqSfcMatche>();
		matchAdapter = new MatchAdapter(this);
		// 设置recyclerView的布局管理
		// LinearLayoutManager -> ListView风格
		// GridLayoutManager -> GridView风格
		// StaggeredGridLayoutManager -> 瀑布流风格
		buy_ctzq_bqc_list.setLayoutManager(new LinearLayoutManager(this));
		buy_ctzq_bqc_list.setAdapter(matchAdapter);

		buy_ctzq_bqc_list_bet.addFooterView(view_buy_ctzq_bet_protocol);
		betAdapter = new BetAdapter(this);
		buy_ctzq_bqc_list_bet.setAdapter(betAdapter);

		String[] parms = new String[2];
		parms[0] = "204";
		JSONObject jsob = new JSONObject();
		try {
			jsob.put("LottID", LotConstants.LOT_ID_BQC);
		} catch (JSONException ex) {
		}
		parms[1] = jsob.toString();
		
		AsyncLoader task = new AsyncLoader();
		task.execute(parms);
	}
	/**
	 * 回退
	 */
	private void onBack() {
		if (view_buy_ctzq_bqc_bet.getVisibility() == View.VISIBLE) {

			MyDialog.Builder dialog = new MyDialog.Builder(this);
			dialog.setTitle("退出提示");
			dialog.setMessage("退出后您的投注将不会保存，确认继续?");
			dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					view_buy_ctzq_bqc_bet.setVisibility(View.GONE);
					buy_ctzq_top_tv_right.setVisibility(View.VISIBLE);
					view_buy_ctzq_bqc_matches.setVisibility(View.VISIBLE);
					onClear();
					dialog.cancel();
				}
			});
			dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			}).create().show();
		} else {
			if(ifPush){
				Intent intent = new Intent(this, JddMainActivity.class);
				startActivity(intent);
			}
			finish();
		}
	}

	/**
	 * 清空
	 */
	private void onClear() {
		// TODO Auto-generated method stub
		for (int i = 0; i < matches.size(); i++) {
			matches.get(i).setBet_win(false);
			matches.get(i).setBet_draw(false);
			matches.get(i).setBet_lose(false);
		}
		betChange();
	}
	/**
	 * 确认合买
	 */
	private void runBetTask2() {
		Intent intent = new Intent();
		intent.putExtra("bs", a_multiple);
		intent.putExtra("AllMoney", betTotal * 2);
		intent.putExtra("IssueID", issueID + "");
		intent.putExtra("IssueName", issue);
		intent.putExtra("LotID", LotConstants.LOT_ID_BQC);

		JSONObject params0 = new JSONObject();
		try {
			if (matchesBet.size() == 4) {
				params0.put("playid", 1902);
				intent.putExtra("PlayTypeId", 1902);
			} else if (matchesBet.size() > 4) {
				params0.put("playid", 1903);
				intent.putExtra("PlayTypeId", 1903);
			}
			params0.put("number", getBetNumber());
		} catch (JSONException e) {
			// e.printStackTrace();
		}
		intent.putExtra("Number", "[" + params0.toString() + "]");

		intent.setClass(this, FaQiHeMaiActivity.class);
		this.startActivityForResult(intent, DefConstants.REQ_CODE_BUYMAIN);
	}
	/**
	 * 格式化所选提示信息
	 *
	 * @param selected
	 * @param
	 * @return
	 */
	private Spanned convertToHtml(int selected) {
		return Html.fromHtml(String.format("已选<font color=red>%1$d</font>场比赛<br />至少选择6场比赛", selected));
	}

	private Spanned convertToHtml(String issue, String endtime) {
		return Html.fromHtml(String.format("第<font color=red>%1$s</font>期     投注截止：<font color=red>%2$s</font>", issue,
				endtime));
	}

	private Spanned convertToHtmlBet(int selected, String endtime) {
		return Html.fromHtml(String.format("共选择<font color=red>%1$d</font>场比赛     投注截止：%2$s", selected, endtime));
	}
	/**
	 * 半全场场次数据任务
	 */
	private class AsyncLoader extends AsyncTask<String, Integer, String> {
		ShowTipDialog showdialog = new ShowTipDialog();
		@Override
		protected void onPreExecute() {
			showdialog.showDialog(CtzqBqcActivity.this);
		}

		@Override
		protected String doInBackground(String... params) {
			String action = params[0];
			String strResult;
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(params[1], UserID, action, getApplicationContext());
			return strResult;
		}
		@Override
		protected void onPostExecute(String result) {
			try {
				if (null != result) {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					if (js.getInt("Code") == 0) {
						Map<String, Object> map = new HashMap<String, Object>();
						map = ConvertJsonToList.getMap(js.getString("Data"));
						issueID = Integer.parseInt(map.get("issueID").toString());
						issue = map.get("issue").toString();
						EndTime = map.get("EndTime").toString();
						buy_ctzq_bqc_issue_and_endtime.setText(convertToHtml(issue, EndTime));
						SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						SimpleDateFormat sdf2 = new SimpleDateFormat("MM-dd HH:mm");
						List<Map<String, Object>> matchesList = ConvertJsonToList.getList(map.get("Matches").toString());
						for (int i = 0; i < matchesList.size(); i++) {
							CtzqSfcMatche match = new CtzqSfcMatche();
							match.setNo(matchesList.get(i).get("No").toString());
							match.setHTeam(matchesList.get(i).get("HTeam").toString());
							match.setVTeam(matchesList.get(i).get("VTeam").toString());

							match.setMatchTime(sdf2.format(sdf1.parse(matchesList.get(i).get("MatchTime").toString())));

							String[] ouodds = matchesList.get(i).get("OuOdds").toString().split(" ");
							if (ouodds.length == 3) {
								match.setOuOdds_win(ouodds[0]);
								match.setOuOdds_draw(ouodds[1]);
								match.setOuOdds_lose(ouodds[2]);
							} else {
								match.setOuOdds_win("-");
								match.setOuOdds_draw("-");
								match.setOuOdds_lose("-");
							}
							match.setBet_win(false);
							match.setBet_draw(false);
							match.setBet_lose(false);
							match.setBet_dan(false);
							matches.add(match);
						}
						betChange();
					} else {
						buy_ctzq_bqc_issue_and_endtime.setVisibility(View.GONE);
						noDataView.setVisibility(View.VISIBLE);
					}
				}
			} catch (Exception e) {
			} finally {
				showdialog.closeDialog();
			}
		}
	}
	/**
	 * 半全场投注任务
	 */
	private class AsyncBetLoader extends AsyncTask<String, Integer, String> {
		ShowTipDialog showdialog = new ShowTipDialog();

		@Override
		protected void onPreExecute() {
			showdialog.showDialog(CtzqBqcActivity.this);
		}

		@Override
		protected String doInBackground(String... params) {
			String action = params[0];
			String strResult;

			try {
				JSONObject param = new JSONObject();
				JSONObject params0 = new JSONObject();
				if (matchesBet.size() == 4) {
					params0.put("playid", 201);
				} else if (matchesBet.size() > 4) {
					params0.put("playid", 202);
				}
				params0.put("number", getBetNumber());

				param.put("SchemeType", 1); // 方案类型 1自购，2合买，3保存 1
				param.put("BetType", 1); // 投注类型 1选号投注 2单式上传 3先发后传 1
				param.put("BonusScale", 0); // 佣金比例
				param.put("AssureShare", 0); // 保底金额
				param.put("Description", ""); // 方案描述
				param.put("OpenUserList", ""); // 招股对象
				param.put("SecrecyLevel", 4); // 安全级别
				param.put("BuyShare", betTotal * a_multiple * 2); // 购买份数
				// 自购等于方案金额
				param.put("Multiple", a_multiple); // 倍数
				param.put("LotteryID", LotConstants.LOT_ID_JQC); // 彩种ID
				param.put("IssueID", issueID); //期次ID
				param.put("IssueName", issue);
				param.put("Number", "[" + params0.toString() + "]"); // 方案内容
				param.put("Money", betTotal * a_multiple * 2); // 方案金额
				paramsStr = param.toString();
				String UserID = ApplicationData.getInstance().getUserID();
				strResult = GetRequestParams.getRequestUserIDResult(param.toString(), UserID, action,
						getApplicationContext());
				return strResult;
			} catch (JSONException e) {
				// e.printStackTrace();
				return null;
			}
		}

		@Override
		protected void onPostExecute(String result) {
			try {
				if (null != result) {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					int buy_icon;
					if (js.getInt("Code") != 0) {
						buy_icon = R.drawable.buy_failure;
						if(js.getString("Data").contains(Constants.BALANCE_BUZU)){
							Intent intent = new Intent();
							intent.setClass(CtzqBqcActivity.this, JddRechargeListActivity.class);
							intent.putExtra("params", paramsStr);
							startActivityForResult(intent, DefConstants.REQ_CODE_NO_MONEY_2_RECHARGE);
						} else {
							new ShowTipDialog().showBuyInfo(CtzqBqcActivity.this, js.getString("Data"), "购买失败", buy_icon,
									paramsStr);
						}
					} else {
						Map<String, Object> map = new HashMap<String, Object>();
						map = ConvertJsonToList.getMap(js.getString("Data"));

						buy_icon = R.drawable.buy_success;
						String msg = "发起任选9第" + issue + "期购买方案\n\n我的认购：" + (betTotal * a_multiple * 2)/* + "元\n账户余额："
								+ map.get("Balance").toString()*/ + "元"+"\n方案编号："+js.getString("Data").toString();
						new ShowTipDialog().showBuyInfo(CtzqBqcActivity.this, msg, "投注成功", buy_icon, paramsStr);

						// 存贮数据
						MyPreference.getInstance(CtzqBqcActivity.this).storeBLotID(LotConstants.LOT_ID_ZQ_RX9);

					}
				}
			} catch (JSONException e) {
				// e.printStackTrace();
			} finally {
				showdialog.closeDialog();
			}
		}

	}
	/**
	 * 自定义任选9数据适配器
	 */
	private class MatchAdapter extends RecyclerView.Adapter<MatchAdapter.ViewHolder> {

		private Context mContext;
		public MatchAdapter( Context mContext) {
			this.mContext=mContext;
		}

		@Override
		public MatchAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
			View itemView= LayoutInflater.from(mContext).inflate(R.layout.buy_ctzq_bqc_list_item,parent,false);
			ViewHolder mHolder=new ViewHolder(itemView);
			return mHolder;
		}

		@Override
		public void onBindViewHolder(MatchAdapter.ViewHolder holder, int position) {
			final CtzqSfcMatche match = matches.get(position);
			holder.buy_ctzq_bqc_list_item_no.setText(match.getNo());

			holder.buy_ctzq_bqc_list_item_matchtime.setText(match.getMatchTime());

			holder.buy_ctzq_bqc_list_item_bet_win.setSelected(match.isBet_win());
			if (match.isBet_win()) {
				holder.buy_ctzq_bqc_list_item_bet_win.setText(Html.fromHtml("<font size='15dip' color='#ffffff'>"
						+ match.getHTeam() + "</font><br>" + "胜"+match.getOuOdds_win()));
			} else {
				holder.buy_ctzq_bqc_list_item_bet_win.setText(Html.fromHtml("<font size='15dip' color='#000000'>"
						+ match.getHTeam() + "</font><br>" + "胜"+match.getOuOdds_win()));
			}
			// holder.buy_ctzq_rx9_list_item_bet_win.setText(convertToHtml(3,
			// match.getOuOdds_win()));
			holder.buy_ctzq_bqc_list_item_hteam.setText(match.getOuOdds_win());

			holder.buy_ctzq_bqc_list_item_bet_win.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					match.setBet_win(!match.isBet_win());
					betChange();
				}
			});


			holder.buy_ctzq_bqc_list_item_bet_draw.setSelected(match.isBet_draw());

			if (match.isBet_draw()) {
				holder.buy_ctzq_bqc_list_item_bet_draw.setText(Html
						.fromHtml("<font size='15dip' color='#ffffff'>VS</font><br>" + "平"+match.getOuOdds_draw()));
			} else {
				holder.buy_ctzq_bqc_list_item_bet_draw.setText(Html
						.fromHtml("<font size='15dip' color='#000000'>VS</font><br>" + "平"+match.getOuOdds_draw()));
			}
			holder.buy_ctzq_bqc_list_item_hteam_vs_vteam.setText(match.getOuOdds_draw());
			holder.buy_ctzq_bqc_list_item_bet_draw.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					match.setBet_draw(!match.isBet_draw());
					betChange();
				}
			});

			holder.buy_ctzq_bqc_list_item_bet_lose.setSelected(match.isBet_lose());

			if (match.isBet_lose()) {
				holder.buy_ctzq_bqc_list_item_bet_lose.setText(Html.fromHtml("<font size='15dip' color='#ffffff'>"
						+ match.getVTeam() + "</font><br>" + "胜"+match.getOuOdds_lose()));
			} else {
				holder.buy_ctzq_bqc_list_item_bet_lose.setText(Html.fromHtml("<font size='15dip' color='#000000'>"
						+ match.getVTeam() + "</font><br>" + "胜"+match.getOuOdds_lose()));
			}
			holder.buy_ctzq_bqc_list_item_vteam.setText(match.getOuOdds_lose());

			holder.buy_ctzq_bqc_list_item_bet_lose.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					match.setBet_lose(!match.isBet_lose());
					betChange();
				}
			});
		}

		@Override
		public int getItemCount() {
			return matches.size();
		}
		/**
		 * RecyclerView的Adapter需要一个ViewHolder必须要extends RecyclerView.ViewHolder
		 */
		public  class ViewHolder extends RecyclerView.ViewHolder {
			public TextView buy_ctzq_bqc_list_item_no;
			public TextView buy_ctzq_bqc_list_item_hteam;
			public TextView buy_ctzq_bqc_list_item_vteam;
			public TextView buy_ctzq_bqc_list_item_hteam_vs_vteam;
			public TextView buy_ctzq_bqc_list_item_matchtime;
			public TextView buy_ctzq_bqc_list_item_bet_win;
			public TextView buy_ctzq_bqc_list_item_bet_draw;
			public TextView buy_ctzq_bqc_list_item_bet_lose;
			public ViewHolder(View itemView) {
				super(itemView);
				// 在创建的时候利用传递过来的View去findViewById
				buy_ctzq_bqc_list_item_no= (TextView) itemView.findViewById(R.id.buy_ctzq_bqc_list_item_no);
				buy_ctzq_bqc_list_item_hteam= (TextView) itemView.findViewById(R.id.buy_ctzq_bqc_list_item_hteam);
				buy_ctzq_bqc_list_item_vteam= (TextView)itemView. findViewById(R.id.buy_ctzq_bqc_list_item_vteam);
				buy_ctzq_bqc_list_item_hteam_vs_vteam= (TextView)itemView. findViewById(R.id.buy_ctzq_bqc_list_item_hteam_vs_vteam);
				buy_ctzq_bqc_list_item_matchtime= (TextView)itemView. findViewById(R.id.buy_ctzq_bqc_list_item_matchtime);
				buy_ctzq_bqc_list_item_bet_win= (TextView) itemView.findViewById(R.id.buy_ctzq_bqc_list_item_bet_win);
				buy_ctzq_bqc_list_item_bet_draw= (TextView)itemView. findViewById(R.id.buy_ctzq_bqc_list_item_bet_draw);
				buy_ctzq_bqc_list_item_bet_lose= (TextView) itemView.findViewById(R.id.buy_ctzq_bqc_list_item_bet_lose);
			}
		}

	}
	/**
	 * 自定义任选9投注适配器
	 */
	private class BetAdapter extends BaseAdapter {

		private Context context;

		public BetAdapter(Context context) {
			this.context = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return matchesBet.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return matchesBet.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final CtzqSfcMatche match = matchesBet.get(position);
			BetAdapter.Holder holder = null;

			if (convertView == null) {
				convertView = LayoutInflater.from(context).inflate(R.layout.buy_ctzq_rx9_list_item_bet, null);

				holder = new BetAdapter.Holder();
				holder.buy_ctzq_rx9_list_item_no = (TextView) convertView.findViewById(R.id.buy_ctzq_rx9_list_item_no);
				holder.buy_ctzq_rx9_list_item_hteam = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_hteam);
				holder.buy_ctzq_rx9_list_item_vteam = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_vteam);
				holder.buy_ctzq_rx9_list_item_bet_win = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_bet_win);
				holder.buy_ctzq_rx9_list_item_bet_draw = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_bet_draw);
				holder.buy_ctzq_rx9_list_item_bet_lose = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_bet_lose);
				holder.buy_ctzq_rx9_list_item_delete = (ImageView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_delete);

				convertView.setTag(holder);
			} else {
				holder = (BetAdapter.Holder) convertView.getTag();
			}

			holder.buy_ctzq_rx9_list_item_no.setText(match.getNo());
			holder.buy_ctzq_rx9_list_item_hteam.setText(match.getHTeam());
			holder.buy_ctzq_rx9_list_item_vteam.setText(match.getVTeam());
			holder.buy_ctzq_rx9_list_item_bet_win.setSelected(match.isBet_win());
			holder.buy_ctzq_rx9_list_item_bet_draw.setSelected(match.isBet_draw());
			holder.buy_ctzq_rx9_list_item_bet_lose.setSelected(match.isBet_lose());


			holder.buy_ctzq_rx9_list_item_delete.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					for (int i = 0; i < matches.size(); i++) {
						if (matches.get(i).getNo().equals(match.getNo())) {
							matches.get(i).setBet_win(false);
							matches.get(i).setBet_draw(false);
							matches.get(i).setBet_lose(false);
							matches.get(i).setBet_dan(false);
						}
					}
					if (matches.size() < 4) {
						Toast.makeText(CtzqBqcActivity.this, "不能少于4场！", Toast.LENGTH_SHORT).show();
					} else {
						matchesBet.remove(match);
						betAdapter.notifyDataSetChanged();
						showBetTotal();
					}
				}
			});
			holder.buy_ctzq_rx9_list_item_delete.setEnabled(matchesBet.size() > 4);
			return convertView;
		}
		class Holder {
			TextView buy_ctzq_rx9_list_item_no;
			TextView buy_ctzq_rx9_list_item_hteam;
			TextView buy_ctzq_rx9_list_item_vteam;
			TextView buy_ctzq_rx9_list_item_bet_win;
			TextView buy_ctzq_rx9_list_item_bet_draw;
			TextView buy_ctzq_rx9_list_item_bet_lose;
			ImageView buy_ctzq_rx9_list_item_delete;
		}
	}
	/**
	 * 获取投注内容
	 *
	 * @return
	 */
	private String getBetNumber() {
		String number = "";

		for (int i = 0; i < matches.size(); i++) {
			String ball = "";
			if (matches.get(i).isBet_win())
				ball += "3";
			if (matches.get(i).isBet_draw())
				ball += "1";
			if (matches.get(i).isBet_lose())
				ball += "0";

			if (ball.equals(""))
				number += "#";
			else
				number += ball;

			number += ",";
		}

		number = number.substring(0, number.length() - 1);
		return number;
	}

	/**
	 * 显示底部结果
	 *
	 */
	private void showBetTotal() {
		buy_ctzq_bqc_matches_and_endtime.setText(convertToHtmlBet(getBetCount(), EndTime));
		betTotal = getBetTotal();
		buy_ctzq_bottom_tv_title_bet.setText("共" + betTotal * 2 * a_multiple + "元");
	}
	/**
	 * 倍数输入变化
	 */
	TextWatcher textWatcher = new TextWatcher() {
		private boolean isChanged = false;

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub
		}
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			// TODO Auto-generated method stub
		}
		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			if (isChanged) {
				return;
			}
			isChanged = true;
			if (!buy_ctzq_bottom_et_a_multiple.getText().toString().equals("")) {

				int bs = Integer.parseInt(s.toString());
				String str2 = s.toString().trim().replaceFirst("^0*", "");// 正则去除
				if (bs < 1) {
					Toast.makeText(CtzqBqcActivity.this, R.string.the_minimum_ratio_of_one, Toast.LENGTH_SHORT).show();
					buy_ctzq_bottom_et_a_multiple.setText("1");
					buy_ctzq_bottom_et_a_multiple.selectAll();
					a_multiple = 1;
				} else if (bs > 99) {
					Toast.makeText(CtzqBqcActivity.this, R.string.the_maximum_ratio_of_nine_hundred_and_ninety_nine,
							Toast.LENGTH_SHORT).show();
					buy_ctzq_bottom_et_a_multiple.setText("99");
					buy_ctzq_bottom_et_a_multiple.selectAll();
					a_multiple = 99;
				} else {
					buy_ctzq_bottom_et_a_multiple.setText(str2);
					buy_ctzq_bottom_et_a_multiple.setSelection(buy_ctzq_bottom_et_a_multiple.length());
					a_multiple = Integer.parseInt(str2.toString());
				}
			} else {
				buy_ctzq_bottom_et_a_multiple.setText("1");
				buy_ctzq_bottom_et_a_multiple.selectAll();
				a_multiple = 1;
			}
			buy_ctzq_bottom_tv_title_bet.setText("共" + betTotal * 2 * a_multiple + "元");
			isChanged = false;
			buy_ctzq_bottom_et_a_multiple.invalidate();
		}
	};
	/**
	 * 计算投注总数
	 *
	 * @return
	 */
	private int getBetTotal() {

		int total;
		if (matchesBet.size() == 4) {
			total = 1;
			for (int i = 0; i < matchesBet.size(); i++) {
				int bet = getTeamCount(matchesBet.get(i));
				total *= bet;
			}
		} else if (matchesBet.size() > 4) {
			int a[] = new int[matchesBet.size()];
			for (int i = 0; i < matchesBet.size(); i++) {
				a[i] = i;
			}
			List<int[]> com = FactoryNum.combine1(a, 4);
			total = 0;
			for (int i = 0; i < com.size(); i++) {
				int[] mat = com.get(i);
				int mc = 1;
				mc = mc * getTeamCount(matchesBet.get(mat[0]))
						* getTeamCount(matchesBet.get(mat[1]))
						* getTeamCount(matchesBet.get(mat[2]))
						* getTeamCount(matchesBet.get(mat[3]));
				total += mc;
			}
		} else {
			total = 0;
		}
		return total;
	}
	/**
	 * 更新列表及选中信息
	 */
	private void betChange() {
		matchAdapter.notifyDataSetChanged();
		buy_ctzq_bottom_tv_title.setText(convertToHtml(getBetCount()));
	}
	/**
	 * 切换至投注界面
	 */
	private void showBetView() {
		view_buy_ctzq_bqc_matches.setVisibility(View.GONE);
		view_buy_ctzq_bqc_bet.setVisibility(View.VISIBLE);
		buy_ctzq_top_tv_right.setVisibility(View.INVISIBLE);
		a_multiple = 1;
		buy_ctzq_bottom_et_a_multiple.setText("1");
		matchesBet.clear();
		for (int i = 0; i < matches.size(); i++) {
			CtzqSfcMatche match = matches.get(i);
			if (match.isBet_win() || match.isBet_draw() || match.isBet_lose()) {
				matchesBet.add(match);
			}
		}
		betAdapter.notifyDataSetChanged();
		showBetTotal();
	}
	/**
	 * 获取当前已选择的比赛数目
	 */
	private int getBetCount() {
		int count = 0;
		for (int i = 0; i < matches.size(); i++) {
			CtzqSfcMatche match = matches.get(i);
			if (match.isBet_win() || match.isBet_draw() || match.isBet_lose()) {
				count++;
			}
		}
		return count;
	}
	/**
	 * 获取当前比赛投注种类（胜平负）数
	 *
	 * @param match
	 * @return
	 */
	private int getTeamCount(CtzqSfcMatche match) {
		int bet = 0;
		if (match.isBet_win())
			bet++;
		if (match.isBet_draw())
			bet++;
		if (match.isBet_lose())
			bet++;
		return bet;
	}
	/** 显示文字提示 */
	private void showTip(String tip) {
		Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
	}
	/**
	 * 登录检测
	 *
	 * @return
	 */
	public boolean checkUserLogin() {
		if (!ApplicationData.getInstance().getLoginName().equals("")
				&& !ApplicationData.getInstance().getLoginPwd().equals("")
				|| !ApplicationData.getInstance().getUserID().equals("")) {
			return true;
		} else {
			return false;
		}
	}
}
